package com.ideafactory.client.ybservice.xmpphandler;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Handler;
import android.os.Message;
import android.os.SystemProperties;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Surface;
import android.view.View;


import com.ideafactory.client.utils.HandleMessageUtils;
import com.ideafactory.client.utils.HeartBeatClient;
import com.ideafactory.client.ybservice.AppActivityManager;

import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by LiuShao on 2016/5/11.
 */
public class ScreenShot {

    private static ScreenShot screenShot = null;

    private ScreenShot() {
    }

    public static ScreenShot getInstanse() {
        if (screenShot == null) {
            synchronized (ScreenShot.class) {
                if (screenShot == null) {
                    screenShot = new ScreenShot();
                }
            }
        }
        return screenShot;
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
           switch (msg.what){
               case 111:
                   try {
                       Bitmap bitmap = snapShotWithStatusBar();
                       String path = ResourceUpdate.SCREEN_CACHE_PATH;
                       File file = new File(path);
                       if (!file.exists()) {
                           file.mkdirs();
                       }
                       String sid = HeartBeatClient.getDeviceNo();
                       String filePath = path + sid + ".png";
                       FileOutputStream fileOutputStream = new FileOutputStream(filePath);
                       // 图片压缩
                       bitmap.compress(Bitmap.CompressFormat.JPEG, 20, fileOutputStream);
                       fileOutputStream.close();

                       // 图片上传
                       sendCutFinish(sid, filePath);
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
                   break;
           }


        }
    };
    /**
     * 屏幕截图
     */
    public  void shootScreen() {
            // 图片截取
            handler.sendEmptyMessage(111);
    }

    private void sendCutFinish(String sid, final String filePath) {
        final  HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("sid", sid);
        HandleMessageUtils.getInstance().runInThread(new Runnable() {
                       @Override
                       public void run() {
                           communication02(ResourceUpdate.SCREEN_UPLOAD_URL, params, filePath, "screenimage");
                                                                              }
                   });

    }
    /**
     * @param urlString 对应的URL 页面  只发送普通数据 ,调用此方法
     * @param params    需要发送的相关数据 包括调用的方法
     * @param imageuri  图片或文件手机上的地址 如:sdcard/photo/123.jpg
     * @param img       图片名称
     * @return Json
     */
    public static void communication02(String urlString, Map<String, Object> params, String imageuri, String img) {
        String result = "";

        String end = "\r\n";
        // 是我定义的上传URL
        String MULTIPART_FORM_DATA = "multipart/form-data";
        String BOUNDARY = "---------7d4a6d158c9"; // 数据分隔线
        String imguri = "";
        if (!imageuri.equals("")) {
            imguri = imageuri.substring(imageuri.lastIndexOf("/") + 1);// 获得图片或文件名称
        }
        if (!urlString.equals("")) {
            try {
                URL url = new URL(urlString);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true);// 允许输入
                conn.setDoOutput(true);// 允许输出
                conn.setUseCaches(false);// 不使用Cache
                conn.setConnectTimeout(6000);// 6秒钟连接超时
                conn.setReadTimeout(60000);// 6秒钟读数据超时
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Charset", "UTF-8");
                conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);

                StringBuilder sb = new StringBuilder();

                // 上传的表单参数部分，格式请参考文章
                for (Map.Entry<String, Object> entry : params.entrySet()) {// 构建表单字段内容
                    sb.append("--");
                    sb.append(BOUNDARY);
                    sb.append("\r\n");
                    sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
                    sb.append(entry.getValue());
                    sb.append("\r\n");
                }

                sb.append("--");
                sb.append(BOUNDARY);
                sb.append("\r\n");

                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                dos.write(sb.toString().getBytes());

                if (!imageuri.equals("") && !imageuri.equals(null)) {
                    dos.writeBytes("Content-Disposition: form-data; name=\"" + img + "\"; filename=\"" + imguri + "\"" + "\r\n" + "Content-Type: image/jpeg\r\n\r\n");
                    FileInputStream fis = new FileInputStream(imageuri);
                    byte[] buffer = new byte[1024]; // 8k
                    int count = 0;
                    while ((count = fis.read(buffer)) != -1) {
                        dos.write(buffer, 0, count);
                    }
                    dos.writeBytes(end);
                    fis.close();
                }
                dos.writeBytes("--" + BOUNDARY + "--\r\n");
                dos.flush();

                InputStream is = conn.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, "utf-8");
                BufferedReader br = new BufferedReader(isr);
                result = br.readLine();
            } catch (Exception e) {
                e.printStackTrace();
                result = "{\"ret\":\"898\"}";
            }
        }
    }

    // 截屏,通用接口.
    public Bitmap snapShotWithStatusBar() {
        View view = AppActivityManager.getAppActivityManager().currentActivity().getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        DisplayMetrics dm = new DisplayMetrics();
        AppActivityManager.getAppActivityManager().currentActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;  // 获取屏幕的宽  像素
        int height = dm.heightPixels; // 获取屏幕的高  像素
        Bitmap dragimg=Bitmap.createScaledBitmap(bmp, width, height, true);
        view.destroyDrawingCache();
        return dragimg;
    }

}
